﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Com.CMS263.Util
{
    

    public static class AdminLoginCookie
    {
        //最后一次登陆超时的用户名称(永不过期)
        public const string AdminLoginCookieLastOverTimeUserName = "LoginInfoLastOverTimeUserName";
        public const string AdminLoginCookieName = "AdminLoginInfo";
        public const int ExpiredMinute = 30;
        /// <summary>
        /// cookies的域
        /// </summary>
        public static string CookiesDomain = "";

        /// <summary>
        /// 保存登录cookie
        /// </summary>
        /// <param name="info"></param>
        public static void AdminSaveLoginInfo(AdminLoginInfo info)
        {
            HttpCookie cookie = new HttpCookie(AdminLoginCookieName);
            if (!string.IsNullOrEmpty(CookiesDomain))
            {
                cookie.Domain = CookiesDomain;
            }
            cookie.Values.Add("NE", info.UserName);
            cookie.Values.Add("AU", info.Authentication);
            cookie.Values.Add("ID", info.UserID.ToString());
            cookie.Values.Add("RD", info.roleID.ToString());
            try
            {
            cookie.Values.Add("PW", info.Power.ToString());
            }
            catch 
            {
                cookie.Values.Add("PW", "");
               
            }
            cookie.Values.Add("AT", info.ActionTime.ToString("yyyy-MM-dd HH:mm:ss"));
            HttpContext.Current.Response.AppendCookie(cookie);

            #region 最后一次登陆超时的用户名称(永不过期)
            HttpCookie cookie2 = new HttpCookie(AdminLoginCookieLastOverTimeUserName);
            cookie2.Expires = DateTime.MaxValue;
            cookie2.Values.Add("NE", info.UserName);
            HttpContext.Current.Response.AppendCookie(cookie2);
            #endregion
        }
        /// <summary>
        /// 清除登录cookie
        /// </summary>
        public static void ClearAdminLoginInfo()
        {
            HttpCookie cookie = new HttpCookie(AdminLoginCookieName);
            cookie.Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies.Add(cookie);

            HttpCookie cookie2 = new HttpCookie(AdminLoginCookieLastOverTimeUserName);
            cookie2.Expires = DateTime.MinValue;
            HttpContext.Current.Response.Cookies.Add(cookie2);
        }
        /// <summary>
        /// 计算认证信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static string GetAuthentication(AdminLoginInfo info)
        {
            
            return (info.ToString().GetHashCode() + 999).ToString();
        }

        /// <summary>
        /// 获取最后一次登陆超时的用户名称(永不过期)
        /// </summary>
        /// <returns></returns>
        public static string GetLoginLastOverTimeUserName()
        {
            string username = null;
            HttpCookie cookie = HttpContext.Current.Request.Cookies[AdminLoginCookieLastOverTimeUserName];
            if (cookie != null)
                username = cookie.Values["NE"];
            return username;
        }

        /// <summary>
        /// 获取登录信息，超时将返回null
        /// </summary>
        /// <returns></returns>
        public static AdminLoginInfo GetLoginInfo()
        {
            AdminLoginInfo info = null;
            HttpCookie cookie = HttpContext.Current.Request.Cookies[AdminLoginCookieName];
            if (cookie != null)
            {
                DateTime ActionTime = DateTime.Parse(cookie.Values["AT"]);
                if (IsExpired(ActionTime))
                {
                    ClearAdminLoginInfo();
                }
                else
                {
                    info = new AdminLoginInfo();
                    info.ActionTime = DateTime.Now;
                  
                    info.UserID = int.Parse(cookie.Values["ID"]);
                    info.roleID = int.Parse(cookie.Values["RD"]);
                    info.UserName = cookie.Values["NE"];
                    info.Authentication = cookie.Values["AU"];
                    info.Power = cookie.Values["PW"];
                    AdminSaveLoginInfo(info);
                }

            }
            return info;
        }

        /// <summary>
        /// 判断是否过期
        /// </summary>
        /// <param name="ActionTime"></param>
        /// <returns></returns>
        private static bool IsExpired(DateTime ActionTime)
        {
            //return DateTime.Now.AddMinutes(ExpiredMinute) > ActionTime;
            return ActionTime.AddMinutes(ExpiredMinute) < DateTime.Now;
        }
        /// <summary>
        /// 
        /// </summary>
        public static void Check()
        {
            AdminLoginInfo info = GetLoginInfo();
            if (!(info != null && Authenticate(info)))
            {
                StringUtil.Alert("您还没有登录,或者登陆已超时，请重新登录", "userLogin.aspx");
            }
        }
        
        /// <summary>
        /// 验证合法性（是否被篡改）
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static bool Authenticate(AdminLoginInfo info)
        {
            string Authentication = GetAuthentication(info);
            return info.Authentication == Authentication;
        }

        /// <summary>
        /// 是否已登录（null或被篡改将返回false）
        /// </summary>
        /// <returns></returns>
        public static bool IsUserLogin()
        {
            AdminLoginInfo info = GetLoginInfo();
            return (info != null && Authenticate(info));
        }

        public static void SaveLoginInfo(AdminLoginInfo li)
        {
            HttpCookie cookie = new HttpCookie(AdminLoginCookieName);
            if (!string.IsNullOrEmpty(CookiesDomain))
            {
                cookie.Domain = CookiesDomain;
            }
            cookie.Values.Add("NE", li.UserName);
            cookie.Values.Add("AU", li.Authentication);
            cookie.Values.Add("ID", li.UserID.ToString());
            cookie.Values.Add("RD", li.roleID.ToString());
            try
            {
                cookie.Values.Add("PW", li.Power.ToString());
            }
            catch
            {
                cookie.Values.Add("PW", "");

            }
            cookie.Values.Add("AT", li.ActionTime.ToString("yyyy-MM-dd HH:mm:ss"));
            HttpContext.Current.Response.AppendCookie(cookie);
        }
    }
    /// <summary>
    /// 用于记录用户登录信息的类
    /// </summary>
    public class AdminLoginInfo
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public int UserID { set; get; }
        /// <summary>
        /// 登录用户名
        /// </summary>
        public string UserName { set; get; }
        /// <summary>
        /// 认证信息
        /// </summary>
        public string Authentication { set; get; }

        /// <summary>
        /// 活动时间
        /// </summary>
        public DateTime ActionTime { set; get; }
        /// <summary>
        /// 用户权限
        /// </summary>
        public string Power { set;get;}
        /// <summary>
        /// 用户角色编号
        /// </summary>
        public int roleID { get; set; }
        ///// <summary>
        ///// 创建时间
        ///// </summary>
        //public DateTime CreateTime { set; get; }

       

        private readonly string AdminConfusion = "2#d_+c.dSo%makelumeradmin";

        public AdminLoginInfo(string userName,int userID,int roleID)
        {
            this.UserName = userName;
            this.UserID = userID;
            this.roleID = roleID;
            this.ActionTime = DateTime.Now;
          
            this.Authentication = AdminLoginCookie.GetAuthentication(this);
            
        }
        public AdminLoginInfo() {  }
        public AdminLoginInfo(string userName, int userID, int roleID, string Power)
        {

            this.UserName = userName;
            this.UserID = userID;
            this.roleID = roleID;
            this.Power = Power;
            this.ActionTime = DateTime.Now;
            this.Authentication = AdminLoginCookie.GetAuthentication(this);
        }
        public override string ToString()
        {
            return this.UserName+this.UserID+this.AdminConfusion+this.roleID;
        }
    }

}
